import scrapy

from scrapys.wudiSpyder.wudiSpyder.items import MatchInfoItem, ZucaiTtgGameItem, \
    UpZucaiTtgGameItem
from lxml import etree
from datetime import datetime

class Wan500LiveZucaiTtgSpider(scrapy.Spider):
    name = "Wan500LiveZucaiTtgSpider"
    allowed_domains = ["500.com"]
    start_urls = [
        "https://live.500.com/4chang.php",  # 足球四场总进球页面
    ]
    def parse(self, response):
        game_expect = response.xpath('//*[@id="sel_expect"]/option/text()').get("data") # //*[@id="sel_expect"]/option[4]
        # 再次去找停售时间
        next_page = "https://www.500.com/static/public/jq4/daigou/xml/{}.xml".format(game_expect)
        yield response.follow(next_page, callback=self.parse_other)

        match_body = response.xpath('//*[@id="table_match"]/tbody')[0]
        match_body_trs = match_body.xpath("tr")
        # 先做一个数据清洗，防止有加时数据数据行
        match_rows = []

        for i in range(len(match_body_trs)):
            if len(match_body_trs[i].xpath("td").extract()) > 1:
                match_rows.append(match_body_trs[i])

        for tr in match_rows:
            fid = tr.xpath("@fid").get("data")  # 500wan比赛id
            status = tr.xpath("@status").get("data")    # 500wan比赛状态，0：未开始，4：已结束
            tds = tr.xpath("td")
            game_no = tds[0].xpath("text()").get("data")             # 场次
            contest = tds[1].xpath("a/text()").get("data")      # 赛事
            match_round = tds[2].xpath("text()").get("data")     # 轮次
            match_time = tds[3].xpath("text()").get("data")     # 比赛时间

            home_team = tds[5].xpath("a/text()").get("data")      # 主队名称
            home_team_url = tds[5].xpath("a/@href").get("data")  # 主队链接
            home_team_ranking = '[0]'
            home_ranking = tds[5].xpath("span/text()").extract()  # 主队排名//*[@id="a1150848"]/td[6]/span
            if len(home_ranking) > 0:
                home_team_ranking = home_ranking
            home_team_score = 0
            home_score = tds[6].xpath("div/a[1]/text()").extract()  # 主队得分
            if len(home_score) > 0:
                home_team_score = home_score

            match_line = tds[6].xpath("div/a[2]/text()").get("data")  # 澳门水位
            away_team_score = 0
            away_score = tds[6].xpath("div/a[3]/text()").extract()  # 客队得分
            if len(away_score) > 0:
                away_team_score = away_score[0]

            away_team = tds[7].xpath("a/text()").get("data")  # 客队名称
            away_team_ranking = '[0]'
            away_ranking = tds[7].xpath("span[@class='gray']/text()").extract()  # 客队排名//*[@id="a1181171"]/td[8]/span[2]
            if len(away_ranking) > 0:
                away_team_ranking = away_ranking
            away_team_url = tds[7].xpath("a/@href").get("data")  # 客队链接

            half_score = tds[8].xpath("text()").extract()   # 半场比分
            to_half_score = half_score[0].split("-")
            home_team_half_score = to_half_score[0].strip()
            away_team_half_score = to_half_score[1].strip()
            if not home_team_half_score:
                home_team_half_score = 0
                away_team_half_score = 0

            odd_s = tds[12].xpath("span[1]/text()").get("data")  # 平均欧赔 - 胜 //*[@id="a1151733"]/td[13]/span[1]
            odd_p = tds[12].xpath("span[2]/text()").get("data")  # 平均欧赔 - 平
            odd_f = tds[12].xpath("span[3]/text()").get("data")  # 平均欧赔 - 负

            # 提取基本信息
            match_item = MatchInfoItem()
            match_item['fid'] = fid
            match_item['match_status'] = status
            match_item['contest'] = contest
            match_item['match_time'] = match_time
            match_item['match_round'] = match_round
            match_item['home_team'] = home_team
            match_item['home_team_ranking'] = home_team_ranking[0]
            match_item['home_team_url'] = home_team_url
            match_item['match_line'] = match_line
            match_item['away_team'] = away_team
            match_item['away_team_ranking'] = away_team_ranking[0]
            match_item['away_team_url'] = away_team_url
            match_item['odds'] = "{},{},{}".format(odd_s, odd_p, odd_f)

            match_item['home_team_half_score'] = home_team_half_score
            match_item['away_team_half_score'] = away_team_half_score
            match_item['home_team_score'] = home_team_score
            match_item['away_team_score'] = away_team_score
            yield match_item

            # 比赛结果：主|客
            home = "0"
            away = "0"
            if status == 4:
                if int(home_team_score)>3:
                    home = "3+"
                else:
                    home = home_team_score

                if int(away_team_score)>3:
                    away = "3+"
                else:
                    away = away_team_score

            game_result = home + "|" + away
            # 提取游戏信息
            game_item = ZucaiTtgGameItem()
            game_item['game_no'] = game_no
            game_item['result'] = game_result
            game_item['fid'] = fid
            game_item['expect'] = game_expect
            yield game_item


    # 处理 胜负彩 停售时间及其他信息
    def parse_other(self, response):
        """
        处理胜负彩的停售时间
        """
        root = etree.fromstring(response.body)
        stop_time = root.xpath('//head/@fsendtime')
        expect = root.xpath('//head/@expect')
        ug_item = UpZucaiTtgGameItem()
        ug_item["stop_time"] = datetime.strptime(stop_time[0], '%Y-%m-%d %H:%M')
        ug_item["expect"] = expect[0]
        yield ug_item